//
//  ViewController.swift
//  Example
//
//  Created by xx on 2025/4/22.
//

import UIKit
import FastSwiftSDK

class BoatViewController: FastViewController,UITextFieldDelegate {

    private lazy var img_bg : UIImageView = {
        let img =  UIImageView.init(image: kImage("bg_junjian"))
        self.view.addSubview(img)
        return  img
    } ()
    
    private lazy var logoView : LogoView = {
        let view =  LogoView()
        self.view.addSubview(view)
        return view
    } ()
    
    private lazy var lbl_deviceName : FastLabel = {
        let lbl =  FastLabel.init(self.deviceName)
        self.view.addSubview(lbl)
        return  lbl
    } ()
    
    private lazy var img_wifi : UIImageView = {
        let img =  UIImageView.init(image: kImage("wifi_n"))
        self.view.addSubview(img)
        return  img
    } ()
    
    private lazy var img_device : UIImageView = {
        let img =  UIImageView.init(image: kImage("boat_n"))
        self.view.addSubview(img)
        return  img
    } ()
    
    private lazy var btn_log : FastButton = {
        let btn = FastButton.init(imgName: "log")
        btn.click = {
            self.logView.isHidden = !self.logView.isHidden
        }
        self.view.addSubview(btn)
        return  btn
    } ()
    
    private lazy var btn_refresh : FastButton = {
        let btn = FastButton.init(imgName: "refresh")
        btn.click = {
            self.refreshDevice()
        }
        self.view.addSubview(btn)
        return  btn
    } ()
    
    private lazy var txt_deviceType : FastTextField = {
        let txt = FastTextField.init(placeholder: "请输入设备名称")
        txt.text = self.deviceName
        txt.backgroundColor = .white
        txt.cornerRadius = 5
        txt.delegate = self
        txt.clearButtonMode = .whileEditing
        self.view.addSubview(txt)
        return  txt
    } ()
    
    private lazy var btn_setName : FastButton = {
        let btn = PublicView.button(title: "设置", style: .backgroundColor) { [weak self] in
            if let text = self?.txt_deviceType.text{
                self?.deviceName = text
                self?.lbl_deviceName.text = text
                self?.refreshDevice()
            }
        }
        self.view.addSubview(btn)
        return  btn
    } ()
    
    // 发动机组视图
    private lazy var view_motor : MotorView = {
        let view =  MotorView.init()
        self.view.addSubview(view)
        return  view
    } ()
    
    // 大炮控制视图
    private lazy var view_bigGun : BigGunView = {
        let view =  BigGunView.init()
        self.view.addSubview(view)
         return  view
    } ()
    
    // 雷达控制视图
    private lazy var view_radar : BoatRadarView = {
        let view =  BoatRadarView.init()
        view.callBack = { [weak self] angle in
        }
        self.view.addSubview(view)
        return  view
    } ()
    
    private lazy var logView : LogView = {
        let view =  LogView.init()
        view.isHidden = true
        self.view.addSubview(view)
        return  view
    } ()
    
    var device:XXDevice?
//    let deviceType = "BOAT"
    var deviceName = "CENTER"
    
    override func viewDidLoad() {
        super.viewDidLoad()
        self.title = "小船测试程序"
    }
    
    override func viewWillAppear(_ animated: Bool) {
        if XXMQTT.shared.connectState == 1{
            self.img_wifi.image = kImage("wifi_on")
        }else{
            self.img_wifi.image = kImage("wifi_n")
        }
        
        refreshDevice()
        registerMsg()
        
        // 设置发动机停止
        view_motor.stopAction()
        
        // 设置大炮转向90度  设置关闭激光
        view_bigGun.isFire = false
        view_bigGun.fireAction()
        view_bigGun.angle = 90
        view_bigGun.turnAction()
        
        // 设置雷达转向90度
        view_radar.angle = 90
        view_radar.dictanceAction()
    }
    
    override func viewDidDisappear(_ animated: Bool) {
        self.view_radar.disMiss()
    }
    
    override func viewWillLayoutSubviews() {
        self.img_bg.snp.makeConstraints { make in
            make.top.left.bottom.right.equalTo(0)
        }
        
        self.lbl_deviceName.snp.makeConstraints { make in
            make.top.equalTo(kNavH+20)
            make.left.equalTo(20)
            make.height.equalTo(40)
            make.width.equalTo(100)
        }
        
        self.img_wifi.snp.makeConstraints { make in
            make.top.equalTo(self.lbl_deviceName)
            make.size.equalTo(40)
            make.left.equalTo(self.lbl_deviceName.snp.right).offset(10)
        }
        
        self.img_device.snp.makeConstraints { make in
            make.top.size.equalTo(self.img_wifi)
            make.left.equalTo(self.img_wifi.snp.right).offset(10)
        }
        
        self.btn_log.snp.makeConstraints { make in
            make.top.size.equalTo(self.img_wifi)
            make.left.equalTo(self.img_device.snp.right).offset(10)
        }
        
        self.btn_refresh.snp.makeConstraints { make in
            make.top.size.equalTo(self.img_wifi)
            make.left.equalTo(self.btn_log.snp.right).offset(10)
        }
        
        self.txt_deviceType.snp.makeConstraints { make in
            make.centerY.equalTo(self.img_wifi)
            make.width.equalTo(150)
            make.height.equalTo(40)
            make.left.equalTo(self.btn_refresh.snp.right).offset(10)
        }
        
        self.btn_setName.snp.makeConstraints { make in
            make.top.size.equalTo(self.img_wifi)
            make.left.equalTo(self.txt_deviceType.snp.right).offset(10)
        }
        
        self.logView.snp.makeConstraints { make in
            make.top.equalTo(self.img_wifi.snp.bottom).offset(10)
            make.left.equalTo(20)
            make.right.equalTo(-20)
            make.height.equalTo(300)
        }
        
        self.view_radar.snp.makeConstraints { make in
            make.top.equalTo(self.img_wifi.snp.bottom).offset(10)
            make.left.equalTo(20)
            make.right.equalTo(-20)
            make.height.equalTo(300)
        }
        
        self.view_motor.snp.makeConstraints { make in
            make.top.equalTo(self.logView.snp.bottom).offset(50)
            make.left.equalTo(20)
            make.width.equalTo(320)
            make.height.equalTo(300)
        }
        
        self.view_bigGun.snp.makeConstraints { make in
            make.top.equalTo(self.logView.snp.bottom).offset(100)
            make.right.equalTo(-20)
            make.width.equalTo(320)
            make.height.equalTo(200)
        }
        self.view.bringSubviewToFront(self.logView)
        self.view.sendSubviewToBack(self.img_bg)
    }
    
    // MARK: - Action
    func refreshDevice(){
        self.device = nil
        for d in XXDeviceManager.shared.deviceList{
            if d.type == self.deviceName && d.state == 1{
                self.device = d
            }
        }
        
        if self.device == nil{
            self.img_device.image = kImage("boat_n")
        }else{
            self.img_device.image = kImage("boat_s")
        }
    }
    
    // 注册消息
    func registerMsg(){
        // 连接状态
        XXListenerManager.shared.registerRoute(XXMQTTRout.connectState.rawValue) { [weak self] massage in
            if massage == "1"{
                self?.img_wifi.image = kImage("wifi_on")
            }else{
                self?.img_wifi.image = kImage("wifi_n")
            }
        }
        
        // 发送消息
        XXListenerManager.shared.registerRoute(XXMQTTRout.didPublishMessage.rawValue) { [weak self] massage in
            if let topic = massage?.dic?.string("topic"),let msg = massage?.dic?.string("msg"),let name = self?.deviceName{
                if topic.contains(name) || msg.contains(name) {
                    self?.logView.addLog(msg)
                }
            }
        }
        
        // 接收消息
        XXListenerManager.shared.registerRoute(XXMQTTRout.didReceiveMessage.rawValue) { [weak self] massage in
            if let topic = massage?.dic?.string("topic"),let msg = massage?.dic?.string("msg"),let name = self?.deviceName{
                if topic.contains(name) || msg.contains(name) {
                    self?.logView.addLog(msg)
                }
            }
        }
    }
    
    func subseribes(){
        guard let device = self.device else {
            return
        }
        var topics:Array<String> = []
        for t in device.topics{
            let topic = "\(device.type)/\(device.mac)/\(t)"
            topics.append(topic)
        }
        XXMQTT.shared.subseribes(topics: topics)
    }
    
    // type  0雷达控制  1动力控制  2大炮控制  3
    func sendMsg(type:Int,msg:String?){
        if type == 0{
            
        }else if type == 1{
            
        }else if type == 2{
            
        }
    }
    
}

// 炮塔控制视图
class BigGunView:FastView {
    
    var callBack:FastIntBlock?
    var isFire:Bool = false
    
    private lazy var lbl_title : FastLabel = {
        let lbl =  FastLabel.init(frame: kFrame(10, 10, 300, 30 ),text: "炮台控制",font: .bold(20),color: .white,textAlignment: .center)
        self.addSubview(lbl)
        return  lbl
    } ()
    
    private lazy var btn_left : FastButton = {
        let btn = FastButton.init(imgName: "left_n")
        btn.setImage(kImage("left_s"), for: .highlighted)
        btn.click = { [weak self] in
            self?.callBack?(1)
            if self?.angle ?? 0 > 10{
                self?.angle -= 10
                self?.turnAction()
            }
        }
        self.addSubview(btn)
        return  btn
    } ()
    
    private lazy var btn_right : FastButton = {
        let btn = FastButton.init(imgName: "right_n")
        btn.setImage(kImage("right_s"), for: .highlighted)
        btn.click = {[weak self] in
            self?.callBack?(2)
            if self?.angle ?? 0 < 180{
                self?.angle += 10
                self?.turnAction()
            }
        }
        self.addSubview(btn)
        return  btn
    } ()
    
    private lazy var btn_send : FastButton = {
        let btn = FastButton.init(imgName: "send_n")
        btn.click = { [weak self] in
            self?.callBack?(3)
            self?.isFire = !(self?.isFire ?? false)
            self?.fireAction()
        }
        self.addSubview(btn)
        return  btn
    } ()
    
    var angle = 90
    
    override func setupUI() {
        self.cornerRadius = 5
        self.backgroundColor = .hex("000000", 0.3)
    }
    // 发射事件
    func fireAction(){
        XXNetWorking.shared.boatBigGunFire(type: self.isFire) { [weak self] tag in
            if tag == 1{
                if self?.isFire ?? false{
                    self?.btn_send.image = kImage("send_s")
                }else{
                    self?.btn_send.image = kImage("send_n")
                }
            }
        }
    }
    
    func turnAction(){
        XXNetWorking.shared.boatBigGunAngle(angle: self.angle) { tag in
            
        }
    }
    
    override func layoutSubviews() {
        
        self.lbl_title.snp.makeConstraints { make in
            make.top.left.equalTo(10)
            make.right.equalTo(-10)
            make.height.equalTo(40)
        }
        
        self.btn_left.snp.makeConstraints { make in
            make.top.equalTo(self.lbl_title.snp.bottom)
            make.left.equalTo(self.lbl_title)
            make.size.equalTo(100)
        }
        
        self.btn_right.snp.makeConstraints { make in
            make.top.size.equalTo(self.btn_left)
            make.left.equalTo(self.btn_left.snp.right).offset(10)
        }
        
        self.btn_send.snp.makeConstraints { make in
            make.top.size.equalTo(self.btn_right)
            make.left.equalTo(self.btn_right.snp.right).offset(10)
        }
    }
}

// 发动机控制视图
class MotorView:FastView {

    var callBack:FastIntBlock?
    
    private lazy var lbl_title : FastLabel = {
        let lbl =  FastLabel.init(frame: kFrame(10, 10, 300, 30 ),text: "发动机组控制",font: .bold(20),color: .white,textAlignment: .center)
        self.addSubview(lbl)
        return  lbl
    } ()
    
    private lazy var btn_top : FastButton = {
        let btn = FastButton.init(imgName: "top_n")
        btn.setImage(kImage("top_s"), for: .highlighted)
        btn.click = { [weak self] in
            self?.callBack?(2)
            XXNetWorking.shared.boatForward { tag in
                if tag == 1{
                    self?.setTurnType(tag: 2)
                }
            }
        }
        self.addSubview(btn)
        return  btn
    } ()
    
    private lazy var btn_left : FastButton = {
        let btn = FastButton.init(imgName: "left_n")
        btn.setImage(kImage("left_s"), for: .highlighted)
        btn.click = { [weak self] in
            XXNetWorking.shared.boatLeft { tag in
                if tag == 1{
                    self?.setTurnType(tag: 1)
                }
            }
            self?.callBack?(1)
        }
        self.addSubview(btn)
        return  btn
    } ()
    
    private lazy var btn_right : FastButton = {
        let btn = FastButton.init(imgName: "right_n")
        btn.setImage(kImage("right_s"), for: .highlighted)
        btn.click = { [weak self] in
            self?.callBack?(3)
            XXNetWorking.shared.boatRight { tag in
                if tag == 1{
                    self?.setTurnType(tag: 3)
                }
            }
        }
        self.addSubview(btn)
        return  btn
    } ()
    
    private lazy var btn_stop : FastButton = {
        let btn = FastButton.init(imgName: "stop_s")
        btn.click = { [weak self] in
            self?.callBack?(0)
            self?.stopAction()
        }
        self.addSubview(btn)
        return  btn
    } ()
    
    override func setupUI() {
        self.cornerRadius = 5
        self.backgroundColor = .hex("000000", 0.3)
    }
    
    func setTurnType(tag:Int){
        btn_left.image = kImage("left_n")
        btn_top.image = kImage("top_n")
        btn_right.image = kImage("right_n")
        btn_stop.image = kImage("stop_n")
        if tag == 1{ // 左
            btn_left.image = kImage("left_s")
        }
        if tag == 2{ // 前
            btn_top.image = kImage("top_s")
        }
        if tag == 3{ // 右
            btn_right.image = kImage("right_s")
        }
        if tag == 0{ // 停止
            btn_stop.image = kImage("stop_s")
        }
    }
    
    func stopAction(){
        XXNetWorking.shared.boatStop { [weak self] tag in
            if tag == 1{
                self?.setTurnType(tag: 0)
            }
        }
    }
    
    override func layoutSubviews() {
        
        self.lbl_title.snp.makeConstraints { make in
            make.top.left.equalTo(10)
            make.right.equalTo(-10)
            make.height.equalTo(40)
        }
        
        self.btn_left.snp.makeConstraints { make in
            make.top.equalTo(self.lbl_title.snp.bottom)
            make.left.equalTo(self.lbl_title)
            make.size.equalTo(100)
        }
        
        self.btn_top.snp.makeConstraints { make in
            make.top.size.equalTo(self.btn_left)
            make.left.equalTo(self.btn_left.snp.right).offset(10)
        }
        
        self.btn_right.snp.makeConstraints { make in
            make.top.size.equalTo(self.btn_left)
            make.left.equalTo(self.btn_top.snp.right).offset(10)
        }
        
        self.btn_stop.snp.makeConstraints { make in
            make.top.equalTo(self.btn_top.snp.bottom).offset(10)
            make.size.equalTo(self.btn_left)
            make.left.equalTo(self.btn_left.snp.right).offset(10)
        }
    }
}

// 雷达控制视图
class BoatRadarView:FastView,UITextFieldDelegate {

    private lazy var lbl_title : FastLabel = {
        let lbl =  FastLabel.init(frame: kFrame(10, 10, 300, 30 ),text: "雷达组控制",font: .bold(20),color: .white,textAlignment: .center)
        self.addSubview(lbl)
        return  lbl
    } ()
    
    private lazy var lbl_angle : FastLabel = {
        let lbl =  FastLabel.init(text: "当前角度：90°",font: .bold(20),color: .white,textAlignment: .center)
        self.addSubview(lbl)
        return  lbl
    } ()
    
    private lazy var logView : LogView = {
        let view =  LogView.init()
        view.backgroundColor = .clear
        self.addSubview(view)
        return  view
    } ()
    
    private lazy var btn_auto : FastButton = {
        let btn = PublicView.button(title: "自动", style: .borderColor) { [weak self] in
            self?.type = 1
            self?.changeType()
        }
        self.addSubview(btn)
        return  btn
    } ()
    
    private lazy var btn_hand : FastButton = {
        let btn = PublicView.button(title: "手动", style: .backgroundColor) { [weak self] in
            self?.type = 0
            self?.changeType()
        }
        self.addSubview(btn)
        return  btn
    } ()
    
    private lazy var txt_angle : FastTextField = {
        let txt = FastTextField.init(placeholder: "请输入角度")
        txt.backgroundColor = .white
        txt.cornerRadius = 5
        txt.keyboardType = .numberPad
        txt.delegate = self
        txt.clearButtonMode = .whileEditing
        self.addSubview(txt)
        return  txt
    } ()
    
    private lazy var btn_move : FastButton = {
        let btn = PublicView.button(title: "转向", style: .backgroundColor) { [weak self] in
            if self?.type == 0{
                if let text = self?.txt_angle.text{
                    if let angle = Int(text){
                        if angle >= 0 && angle <= 180{
                            self?.angle = angle
                            self?.changeAngle()
                        }else{
                            self?.txt_angle.text = "请输入0°-180°范围值"
                        }
                    }
                }
            }else{
                self?.txt_angle.text = "当前为自动模式，请切换至手动模式再控制"
            }
        }
        self.addSubview(btn)
        return  btn
    } ()
    
    private lazy var btn_left_10 : FastButton = {
        let btn = PublicView.button(title: "向左10°", style: .backgroundColor) { [weak self] in
            if self?.type == 0{
                self?.angle -= 10
                if self?.angle ?? 0 < 0{
                    self?.angle = 0
                }
                self?.changeAngle()
            }else{
                self?.txt_angle.text = "当前为自动模式，请切换至手动模式再控制"
            }
        }
        self.addSubview(btn)
        return  btn
    } ()
    
    private lazy var btn_right_10 : FastButton = {
        let btn = PublicView.button(title: "向右10°", style: .backgroundColor) { [weak self] in
            if self?.type == 0{
                self?.angle += 10
                if self?.angle ?? 0 > 180{
                    self?.angle = 180
                }
                self?.changeAngle()
            }else{
                self?.txt_angle.text = "当前为自动模式，请切换至手动模式再控制"
            }
        }
        self.addSubview(btn)
        return  btn
    } ()
    
    var type = 0 // 手动 自动
    var timer:Timer? // 自动转向测距
    var angle = 90 // 默认90度
    var callBack:FastIntBlock?
    var direction = 0 // 0 顺时针 1 逆时针
    
    override func setupUI() {
        self.cornerRadius = 5
        self.backgroundColor = .hex("000000", 0.3)
        self.changeAngle()// 启动初始角度
    }
    
    override func layoutSubviews() {
        
        self.lbl_title.snp.makeConstraints { make in
            make.top.left.equalTo(10)
            make.right.equalTo(-10)
            make.height.equalTo(40)
        }
        
        self.logView.snp.makeConstraints { make in
            make.top.equalTo(self.lbl_title.snp.bottom)
            make.left.equalTo(10)
            make.width.equalTo(300)
            make.bottom.equalToSuperview().offset(-20)
        }
        
        self.btn_auto.snp.makeConstraints { make in
            make.top.equalTo(self.lbl_title.snp.bottom)
            make.left.equalTo(self.logView.snp.right).offset(10)
            make.width.equalTo(60)
            make.height.equalTo(45)
        }
        
        self.btn_hand.snp.makeConstraints { make in
            make.top.size.equalTo(self.btn_auto)
            make.left.equalTo(self.btn_auto.snp.right).offset(10)
        }
        
        self.lbl_angle.snp.makeConstraints { make in
            make.top.equalTo(self.btn_auto)
            make.left.equalTo(self.btn_hand.snp.right).offset(10)
        }
        
        self.txt_angle.snp.makeConstraints { make in
            make.top.equalTo(self.btn_auto.snp.bottom).offset(20)
            make.left.equalTo(self.logView.snp.right).offset(10)
            make.right.equalTo(-10)
            make.height.equalTo(45)
        }
        
        self.btn_left_10.snp.makeConstraints { make in
            make.top.equalTo(self.txt_angle.snp.bottom).offset(20)
            make.left.equalTo(self.logView.snp.right).offset(10)
            make.width.equalTo(60)
            make.height.equalTo(45)
        }
        
        self.btn_right_10.snp.makeConstraints { make in
            make.top.size.equalTo(self.btn_left_10)
            make.left.equalTo(self.btn_left_10.snp.right).offset(10)
        }
        
        self.btn_move.snp.makeConstraints { make in
            make.top.size.equalTo(self.btn_left_10)
            make.left.equalTo(self.btn_right_10.snp.right).offset(10)
        }
    }
    
    // MARK: - action
    public func disMiss(){
        self.timer?.invalidate()
        self.timer = nil
    }
    func changeType(){
        if self.type == 0{
            self.btn_auto.setStyle(.borderColor)
            self.btn_hand.setStyle(.backgroundColor)
            self.timer?.invalidate()
        }else{
            self.btn_auto.setStyle(.backgroundColor)
            self.btn_hand.setStyle(.borderColor)
            self.autoChangeAngle()
        }
    }
    
    func autoChangeAngle(){
        self.angle = 90
        self.direction = 0
        self.changeAngle()
        
        self.timer = Timer.scheduledTimer(withTimeInterval: 5, repeats: true) { [weak self] timer in
            guard var angle = self?.angle else {
                return
            }
            if self?.direction == 0{
                angle += 10
            }else{
                angle -= 10
            }
            
            if angle <= 0{
                angle = 0
                self?.direction = 0
            }
            if angle >= 180{
                angle = 180
                self?.direction = 1
            }
            self?.angle = angle
            self?.changeAngle()
        }
    }
    
    func changeAngle(){
        self.txt_angle.text = nil
        self.txt_angle.resignFirstResponder()
        self.lbl_angle.text = "当前角度：\(self.angle)°"
        self.callBack?(self.angle)
        self.dictanceAction()
    }
    
    func dictanceAction(){
        XXNetWorking.shared.boatRadar(angle: self.angle) { [weak self] str in
            
            let arr = str.split(separator: "/")
            if arr.count > 2{
                let angle = arr[1]
                let distance:Int = Int( arr[2].split(separator: "<")[0]) ?? 0
                if distance > 0{
                    self?.setLog("发现敌人    方向：\(angle)°   距离：\(distance) cm")
                }else{
                    self?.setLog("方向：\(angle)°     未发现敌人")
                }
                
                
            }
            
        }
    }
    
    func setLog(_ str:String){
        self.logView.addLog(str)
    }
    
    // MARK: - txtFiledDelegate
    func textFieldShouldBeginEditing(_ textField: UITextField) -> Bool {
        textField.text = nil
        return true
    }
    
    func textFieldShouldReturn(_ textField: UITextField) -> Bool {
        textField.resignFirstResponder()
        if let text = textField.text{
            if let angle = Int(text){
                if angle <= 0 && angle >= 180{
                    self.txt_angle.text = "请输入0°——180°范围值"
                }
            }
        }
        return true
    }
}
